package com.wondertek.poms.core.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.wondertek.poms.dao.po.SellingPriceTag;
import com.wondertek.poms.dao.pojo.SellingPriceTagPojo;
import com.wondertek.poms.dao.repo.IMamRecommendDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import com.wondertek.poms.common.service.impl.ServiceImpl;
import com.wondertek.poms.core.service.IMamRecommendService;
import com.wondertek.poms.dao.po.MamRecommend;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.List;

/**
 * <p><b>PcProductRuleServiceImpl Description:</b> 二级产品规则 service层实现 </p>
 *
 * @author 窦再兴
 * <p><b>DATE</b> 2020-10-16 15:56:15</p>
 */
@Service
public class MamRecommendImpl extends ServiceImpl<MamRecommend, Long> implements IMamRecommendService {

	@PersistenceContext
    public EntityManager entityManager;
	@Autowired
	private IMamRecommendDao mamRecommendDao;

	@Override
	public MamRecommend deleteLogic(Long id) {
		return null;
	}

	@Override
	public MamRecommend merge(MamRecommend model) {
		return null;
	}

	@Override
	public Page<MamRecommend> findAll(MamRecommend entity, int page, int rows, String sord, String sidx) {
		StringBuffer condition=sqlStringWhere(entity,sord,sidx);
		Object o = entityManager
				.createNativeQuery("select count(*) from ( " + condition.toString() + " ) a").getSingleResult();
		int count = Convert.toInt(o);
		Pageable pageable = getPageable(page - 1, rows, sord, sidx);

		if(count>0){
			Query query=entityManager.createNativeQuery(condition.toString(), MamRecommend.class);
			query.setFirstResult(pageable.getPageNumber() * pageable.getPageSize());
			query.setMaxResults(pageable.getPageSize());
			List<MamRecommend> list=query.getResultList();
			PageImpl<MamRecommend> result=new PageImpl<>(list,pageable,count);
			entityManager.close();
			return result;
		}
		entityManager.close();
		return Page.empty(pageable);
	}

	@Override
	@Transactional
	public void deleteMamRecommend(String ids) {
		String[] idArray = ids.split(",|，");
		for(String id:idArray){
			mamRecommendDao.deleteById(Convert.toLong(id));
		}
	}

	public StringBuffer sqlStringWhere(MamRecommend entity,String sord, String sidx){
		StringBuffer condition=new StringBuffer();
		String sql="select * from MAM_RECOMMEND where 1=1 ";
		condition.append(sql);

		if(StrUtil.isNotBlank(entity.getMamRecommend())){
			condition.append("and MAM_RECOMMEND like '%"+entity.getMamRecommend()+"%' ");
		}
		condition.append("order by "+sidx+" "+sord);
		return condition;
	}
}